package com.alibaba.cirtus.ots.application.adapter.ability.utils;

import com.alibaba.citrus.ots.common.util.NameUtil;
import com.alibaba.citrus.ots.common.util.SpringContextUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcots.model.dto.BaselineQueryScItemByPageRequest;
import com.epoch.app.bcots.model.dto.BatchQueryWarehouseByIdsRequest;
import com.epoch.app.bcots.model.dto.GetScItemUnitInfoRequest;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddressRequest;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryCustomersRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryAddressListResponse;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderDetailBatchGetScItemResponse;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderGetCustomerResponse;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderGetOrganizationResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateOrderDetailBatchGetScItemRequest;
import com.epoch.app.otsunifiedinventory.model.dto.QueryUserByIdRequest;
import com.epoch.app.otsunifiedinventory.model.dto.QueryUserByIdResponse;
import com.epoch.app.otsunifiedinventory.model.dto.WmsSDO;
import com.epoch.app.otsunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.otsunifiedinventory.sdo.enums.AllocateOrderShipTypeEnums;
import com.epoch.app.otsunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.otsunifiedinventory.service.OtsUnifiedInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 一些信息的转换
 * @author: yuhw
 * @date: 2021年10月27日 14:18
 **/
public class InfoUtil {
    private static OtsPlatformEnhanceService otsPlatformEnhanceService;
    private static UnifiedInventoryService unifiedInventoryService;
    private static BaseDataService baseDataService;
    private static EpochLoginUserService epochLoginUserService;
    private static OtsUnifiedInventoryService otsUnifiedInventoryService;
    static {
        otsPlatformEnhanceService = SpringContextUtil.getBean(OtsPlatformEnhanceService.class);
        unifiedInventoryService = SpringContextUtil.getBean(UnifiedInventoryService.class);
        baseDataService = SpringContextUtil.getBean(BaseDataService.class);
        epochLoginUserService = SpringContextUtil.getBean(EpochLoginUserService.class);
        otsUnifiedInventoryService = SpringContextUtil.getBean(OtsUnifiedInventoryService.class);
    }

    private static final String SPLIT = ",";
    // 送达方 售达方可能有多个 只取前一个
    public static String getFirstCode(String code){
        if (StringUtils.isBlank(code)){
            return null;
        }
        String[] array = code.split(SPLIT);
        if (array.length <=0){
            return null;
        }
        return array[0];
    }



    public static Map<String,AllocateOrderGetCustomerResponse> getCustomerMap(List<String> codes){
        BatchQueryCustomersRequest request = new BatchQueryCustomersRequest();
        Map<String,AllocateOrderGetCustomerResponse> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(codes)){
            return map;
        }
        request.setCodes(codes);
        Object obj = otsPlatformEnhanceService.batchQueryCustomers(request);
        if (obj != null){
            JSONObject result = JSON.parseObject(JSON.toJSONString(obj));
            if (result != null){
                JSONArray array = result.getJSONArray("result");
                if ( array != null && array.size() > 0){
                    for (int i =0 ;i<array.size();i++){
                        JSONObject data = array.getJSONObject(i);
                        if (data != null){
                            AllocateOrderGetCustomerResponse response = new AllocateOrderGetCustomerResponse();
                            response.setCustomerName(data.getString("name"));
                            response.setCustomer(data.getString("code"));
                            if (response.getCustomer() != null){
                                map.put(response.getCustomer(),response);
                            }
//                            response.setCustomerAddressName();
                        }

                    }
                }
            }
        }
        return map;
    }

    public static String getDifference(String oldQuantity,String freshQuantity){
        if (StringUtils.isBlank(oldQuantity)){
            return freshQuantity;
        }
        BigDecimal decimal;
        if (StringUtils.isBlank(freshQuantity)){
            decimal = new BigDecimal(oldQuantity.trim());
            return decimal.negate().toString();
        }
        BigDecimal old  = new BigDecimal(oldQuantity.trim());
        BigDecimal fresh = new BigDecimal(freshQuantity.trim());
        decimal = fresh.subtract(old);
        return decimal.toString();

    }

    public static String convertUnit(String unit){
        if ("PC".equalsIgnoreCase(unit)){
            return "件";
        }else if ("TO".equalsIgnoreCase(unit)){
            return "吨";
        }else if ("KG".equalsIgnoreCase(unit)){
            return "千克";
        }else if ("HE".equalsIgnoreCase(unit)){
            return "盒";
        }
        return unit;
    }


    public static String getEmpId(String creator){
        if (StringUtils.isBlank(creator)){
            return null;
        }
        JSONObject js = JSON.parseObject(creator);
        return js.getString("empId");
    }
    public static String getRealName(String userId){
        if (StringUtils.isBlank(userId)){
            return null;
        }
//        if (userId.startsWith("CZ_")){
//            userId = userId.substring("CZ_".length());
//        }
//        LoginUser user = epochLoginUserService.getUserByEmpId(userId);
        QueryUserByIdRequest request = new QueryUserByIdRequest();
        request.setUserId(userId);
        QueryUserByIdResponse queryUserByIdResponse = otsUnifiedInventoryService.queryUserById(request);
        if (queryUserByIdResponse != null){
            Object obj = queryUserByIdResponse.getUser();
            if (obj != null){
                String json = obj.toString();
                if (StringUtils.isNotBlank(json)){
                    String realName = NameUtil.getRealName(json);
                    if ("unknown".equals(realName) || "bot_sap".equals(realName)){
                        return "系统";
                    }
                    return realName;
                }
            }
        }
//        if (user != null){
//            return user.getRealName();
//        }
        return null;
    }


    /**
     * 获取类型描述
     * @param type
     * @return
     */
    public static String getTypeDesc(Integer type){
        for (AllocateOrderTypeEnum value : AllocateOrderTypeEnum.values()) {
            if (Objects.equals(value.getType(),type)){
                return value.getDesc();
            }
        }
        return null;
    }
    /**
     * 单据日期
     * @return
     */
    public static Date docDate(){
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY,16);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        if(now.after(calendar.getTime())){
            calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH) +1);
            return calendar.getTime();
        }else {
            return now;
        }
    }

    public static String add(String old,String v){
        BigDecimal oldBigDecimal;
        BigDecimal vBigDecimal;
        if (StringUtils.isBlank(old)){
            oldBigDecimal = BigDecimal.ZERO;
        }else{
            oldBigDecimal = new BigDecimal(old.trim());
        }
        if (StringUtils.isBlank(v)){
            vBigDecimal = BigDecimal.ZERO;
        }else {
            vBigDecimal = new BigDecimal(v.trim());
        }
        return oldBigDecimal.add(vBigDecimal).toString();
    }

    public static String addNoPoint(String old,String v){
        BigDecimal oldBigDecimal;
        BigDecimal vBigDecimal;
        if (StringUtils.isBlank(old)){
            oldBigDecimal = BigDecimal.ZERO;
        }else{
            oldBigDecimal = new BigDecimal(old.trim());
        }
        if (StringUtils.isBlank(v)){
            vBigDecimal = BigDecimal.ZERO;
        }else {
            vBigDecimal = new BigDecimal(v.trim());
        }
       return oldBigDecimal.add(vBigDecimal).setScale(0,RoundingMode.HALF_UP).toString();
    }


    /**
     * 批量查询仓库信息
     * @param wmsIdList
     * @return
     */
    public static Map<String,WmsSDO> getWmsMap(List<String> wmsIdList){
        Map<String,WmsSDO> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(wmsIdList)){
            return map;
        }
        BatchQueryWarehouseByIdsRequest request = new BatchQueryWarehouseByIdsRequest();
        List<Integer> models = Lists.newArrayList(1,3);
        request.setModelList(models);
        request.setWarehouseIds(wmsIdList);
//        request.setWarehouseIds(Lists.newArrayList());
        Object object = unifiedInventoryService.batchQueryWarehouseByIds(request);
        if (object != null){
            JSONObject js = JSON.parseObject(JSON.toJSONString(object));
            if (js != null){
                JSONArray array = js.getJSONArray("result");
                if (array != null && array.size() > 0 ){
                    for (int i=0;i<array.size();i++){
                        JSONObject data = array.getJSONObject(i);
                        if (data != null){
                            WmsSDO wmsSDO = new WmsSDO();
                            String id = data.getString("id");
                            wmsSDO.setId(id);
                            wmsSDO.setName(data.getString("name"));
                            wmsSDO.setType(data.getString("type"));
                            wmsSDO.setWarehouseId(data.getString("warehouseId"));
                            wmsSDO.setPhone(data.getString("contactPhone"));
                            wmsSDO.setContactPerson(data.getString("contactName"));
                            wmsSDO.setAddress(data.getString("address"));
                            JSONObject features = data.getJSONObject("features");
                            if (features != null){
                                wmsSDO.setInventoryCode(features.getString("warehouseCode"));
                                wmsSDO.setFactoryCode(features.getString("sapFactoryCode"));
                                wmsSDO.setSapCompanyCode(features.getString("sapCompanyCode"));
                                wmsSDO.setSapSalesBPCode(features.getString("sapSaleBPCode"));//有点问题的.
                                wmsSDO.setSapDeliveryBPCode(features.getString("sapDeliveryBPCode"));
                                wmsSDO.setSapInternalDeliveryBPCode(features.getString("sapInternalDeliveryBPCode"));
                                wmsSDO.setSapInternalSalesBPCode(features.getString("sapInternalSalesBPCode"));
                                wmsSDO.setSapSalesOrgId(features.getString("saleOrgId"));
//                                wmsSDO.setSapSalesOrgId(features.getString("sapSaleOrgId"));
//                                wmsSDO.setContactPerson(features.getString("contact"));
//                                wmsSDO.setPhone(features.getString("phone"));
//                                wmsSDO.setAddress(features.getString("address"));

                            }
                            map.put(id,wmsSDO);

                        }
                    }
                }
            }
        }
        return map;
    }


    /**
     * 根据仓库id 包括 查询它的基本信息, 例如名称 电话
     * @param wmsIdList
     * @return
     */
    public static Map<String,String> getWmsNameMap(List<String> wmsIdList){
        Map<String,String> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(wmsIdList)){
            return map;
        }
        BatchQueryWarehouseByIdsRequest request = new BatchQueryWarehouseByIdsRequest();
        List<Integer> models = Lists.newArrayList(1,3);
        request.setModelList(models);
        request.setWarehouseIds(wmsIdList);
//        request.setWarehouseIds(Lists.newArrayList());
        Object object = unifiedInventoryService.batchQueryWarehouseByIds(request);
        if (object != null){
            JSONObject js = JSON.parseObject(JSON.toJSONString(object));
            if (js != null){
                JSONArray array = js.getJSONArray("result");
                if (array != null && array.size() > 0 ){
                    for (int i=0;i<array.size();i++){
                        JSONObject obj = array.getJSONObject(i);
                        if (obj != null){
                            map.put(obj.getString("id"),obj.getString("name"));

                        }
                    }
                }
            }
        }
        return map;
    }


    /**
     * 根据地址code获取客户
     * @param addressCode
     * @return
     */
    public static AllocateOrderGetCustomerResponse getCustomerByAddressCode(String addressCode){
        AllocateOrderGetCustomerResponse response = new AllocateOrderGetCustomerResponse();
        if (StringUtils.isNotBlank(addressCode)){
            List<AllocateOrderGetCustomerResponse> list = getCustomerByAddressCodes(Lists.newArrayList(addressCode));
            if (CollectionUtils.isNotEmpty(list)){
                response = list.get(0);
            }
        }
        return response;
    }





    /**
     * 批量获取客户信息 通过客户地址
     * @param addressCodeList
     * @return
     */
    public static List<AllocateOrderGetCustomerResponse> getCustomerByAddressCodes(List<String> addressCodeList){
        List<AllocateOrderGetCustomerResponse> responses = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(addressCodeList)){
            BatchQueryAddressRequest request = new BatchQueryAddressRequest();
            request.setAddressCodes(addressCodeList);
            Object data = otsPlatformEnhanceService.batchQueryAddress(request);
            if (data == null){
                return responses;
            }
            JSONObject js = JSON.parseObject(JSON.toJSONString(data));
            if (js == null){
                return responses;
            }
            JSONArray array = js.getJSONArray("result");
            if (array != null && array.size() > 0){
                for (int i =0;i<array.size();i++){
                    JSONObject object = array.getJSONObject(i);
                    if (object == null){
                        continue;
                    }
                    AllocateOrderGetCustomerResponse r = new AllocateOrderGetCustomerResponse();
                    r.setCustomerName(object.getString("customerName"));
                    r.setCustomerAddress(object.getString("address"));
                    r.setCustomerAddressName(object.getString("addressName"));
                    r.setCustomer(object.getString("customerCode"));
                    r.setAddressCode(object.getString("addressCode"));
                    r.setSalesOrgId(object.getString("orgSaleOrganizationCode"));
                    responses.add(r);
                }
            }
        }
        return responses;
    }

    public static Date getDate(Long v){
        if (v == null)return null;
        Date date = new Date(v);
        return date;
    }

    public static Boolean getBoolean(Long v){
        if (v == null)return null;
        if (Objects.equals(v,1L))return true;
        return false;
    }
    public static String getBooleanDesc(Long v){
        Boolean b = getBoolean(v);
        return Objects.equals(b,Boolean.TRUE)?"是":"否";
    }
    //累计回复量
    public static Integer addReply(Integer var1,String var2){
        if (var1==null)var1=0;
        if (StringUtils.isBlank(var2))return var1;
        BigDecimal v1 = new BigDecimal(var1);
        BigDecimal v2 = new BigDecimal(var2.trim());
        BigDecimal v = v1.add(v2);
        return v.intValue();

    }

    public static Integer getInt(String v ){
        if (StringUtils.isBlank(v))return 0;
        BigDecimal bigDecimal = new BigDecimal(v.trim());
        return bigDecimal.intValue();
    }

    // 获取组织
    public static AllocateOrderGetOrganizationResponse getOrganizationById(String id){

//        GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//        if (StringUtils.isNotBlank(id)){
//            getOrganiztionByIdRequest.setId(id.trim());
//        }
        BaselineGetOrganizationByIdsRequest baselineGetOrganizationByIdsRequest = new BaselineGetOrganizationByIdsRequest();
        if (StringUtils.isNotBlank(id)){
            baselineGetOrganizationByIdsRequest.setIds(Lists.newArrayList(id));
        }
        AllocateOrderGetOrganizationResponse response = new AllocateOrderGetOrganizationResponse();
        Object obj = baseDataService.baselineGetOrganizationByIds(baselineGetOrganizationByIdsRequest);
        if (obj != null){
            JSONObject json = JSON.parseObject(JSONObject.toJSONString(obj));
            JSONArray array = json.getJSONArray("result");
            if (array != null && array.size() > 0){
                JSONObject object = array.getJSONObject(0);
                if (object != null){
                    JSONObject organizationSDO = object.getJSONObject("organizationSDO");
                    if (organizationSDO != null){
                        response.setName(organizationSDO.getString("name"));
                    }
                }
            }
        }

//        OrganizationSDO org = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
//        AllocateOrderGetOrganizationResponse response = new AllocateOrderGetOrganizationResponse();
//        if (org != null){
//            response.setId(org.getId());
//            response.setName(org.getName());
//            response.setCode(org.getCode());
//        }
        return response;
    }

    /**
     * 获取运输方式描述
     * @param type
     * @return
     */
    public static String getShipMethodDesc(Integer type){
        for (AllocateOrderShipTypeEnums value : AllocateOrderShipTypeEnums.values()) {
            if (Objects.equals(type,value.getType())){
                return value.getDesc();
            }
        }
        return null;
    }


    /** 查询客户 **/
    public static AllocateOrderGetCustomerResponse findCustomer(String code){
        BatchQueryCustomersRequest request = new BatchQueryCustomersRequest();
        AllocateOrderGetCustomerResponse response = new AllocateOrderGetCustomerResponse();
        if (StringUtils.isBlank(code)){
            return response;
        }
        request.setCodes(Lists.newArrayList(code));
        Object obj = otsPlatformEnhanceService.batchQueryCustomers(request);
        if (obj != null){
            JSONObject data = JSONObject.parseObject(JSON.toJSONString(obj));
            if (data != null){
//                JSONObject result = data.getJSONObject("result");
                JSONArray array = data.getJSONArray("result");
                if (array != null && array.size() > 0){
                    JSONObject customer = array.getJSONObject(0);
                    if (customer != null){
                        response.setCustomer(code);
                        response.setCustomerName(customer.getString("name"));
                    }
//                    for (int i=0;i<array.size();i++){
//                        JSONObject customer = array.getJSONObject(i);
//                        if (customer !)
//                    }
                }
            }
        }
        return response;
    }
    //获取客户

    /**
     * 有权限的 慎用
     * @param code
     * @return
     */
    public static AllocateOrderGetCustomerResponse getCustomer(String code) {
        PageQueryAddressListRequest request = new PageQueryAddressListRequest();
        request.setCustomerCode(code);
        PageQueryAddressListResponse response = otsPlatformEnhanceService.pageQueryAddressList(request);
        if (response == null || response.getResult() == null)return null;
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(response.getResult()));
        if (array == null || array.size() == 0)return null;
        JSONObject object = array.getJSONObject(0);
        AllocateOrderGetCustomerResponse r = new AllocateOrderGetCustomerResponse();
        r.setCustomerName(object.getString("customerName"));
        r.setCustomerAddress(object.getString("address"));
        r.setCustomerAddressName(object.getString("addressName"));
        r.setCustomer(code);
        return r;
    }

    /**
     * 获取逻辑仓
     * @param areaId
     * @return
     */
    public static WmsSDO getWmsSDO(String areaId){
        if (StringUtils.isNotBlank(areaId)){
            QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
            queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(areaId));
            QueryCargoZoneByIdResponse shipAreaQuery = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
            return getWmsSDO(shipAreaQuery);
        }
        return new WmsSDO();
    }
    public static WmsSDO getWmsSDO(QueryCargoZoneByIdResponse response){
        WmsSDO wmsSDO = new WmsSDO();
        if (response !=null && CollectionUtils.isNotEmpty(response.getResult())){
            JSONArray array = JSON.parseArray(JSON.toJSONString(response.getResult()));
            if (array != null && array.size() > 0){
                JSONObject data = array.getJSONObject(0);
//                wmsSDO.setInventoryCode(data.getString("code"));
                wmsSDO.setInventoryCode(data.getString("warehouseCode"));
                wmsSDO.setFactoryCode(data.getString("sapFactoryCode"));
                wmsSDO.setSapCompanyCode(data.getString("sapCompanyCode"));
                wmsSDO.setSapSalesBPCode(data.getString("sapSaleBPCode"));//有点问题的.
                wmsSDO.setSapDeliveryBPCode(data.getString("sapDeliveryBPCode"));
                wmsSDO.setSapInternalDeliveryBPCode(data.getString("sapInternalDeliveryBPCode"));
                wmsSDO.setSapInternalSalesBPCode(data.getString("sapInternalSalesBPCode"));
                wmsSDO.setSapSalesOrgId(data.getString("saleOrgId"));
//                wmsSDO.setSapSalesOrgId(data.getString("sapSaleOrgId"));
                wmsSDO.setName(data.getString("name"));
                wmsSDO.setType(data.getString("type"));
                wmsSDO.setWarehouseId(data.getString("warehouseId"));

//                if (StringUtils.isNotBlank(data.getString("features"))){
//                    JSONObject features = JSON.parseObject(data.getString("features"));
//                    if (features != null){
//                        wmsSDO.setSapCompanyCode(features.getString(""));
//                    }
//                }
            }
        }
        return wmsSDO;
    }

//    public static String getUnitFromList(){
//        baseDataService.baselineQueryScItemByPage()
//    }

    public static String getUnit(String scItemId){
        if (StringUtils.isBlank(scItemId)){
            return null;
        }
        GetScItemUnitInfoRequest request = new GetScItemUnitInfoRequest();
        request.setScItemId(scItemId);
        Object info = baseDataService.getScItemUnitInfo(request);
        if (info != null){
            JSONObject obj = JSON.parseObject(JSON.toJSONString(info));
            if (obj != null){
                JSONArray array = obj.getJSONArray("result");
                if (array != null && array.size() > 0){
                    for (int i =0;i<array.size();i++) {
                        JSONObject object = array.getJSONObject(0);
                        if (object !=null ){
                            String specType = object.getString("specType");
                            if ("1".equals(specType) || "1.0".equals(specType)){
                                return object.getString("unitCode");
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    public static String deleteZeroPrefix(String str){
        if (StringUtils.isBlank(str))return null;
        return str.replaceFirst("^0*","");
    }

//    public static AllocateOrderGetAreaResponse getOrgId(String areaId){
//
//    }


    public static String getUnitByOutCode(String outCode){
        String code = deleteZeroPrefix(outCode);
        if (StringUtils.isNotBlank(code)){
            BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest = new BaselineQueryScItemByPageRequest();
            baselineQueryScItemByPageRequest.setOutIdList(Lists.newArrayList(code));
            Object obj = baseDataService.baselineQueryScItemByPage(baselineQueryScItemByPageRequest);
            if (obj != null){
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
                if (jsonObject != null){
                    jsonObject = jsonObject.getJSONObject("result");
                    if (jsonObject != null){
                        jsonObject = jsonObject.getJSONObject("result");
                        if (jsonObject != null){
                            JSONArray array = jsonObject.getJSONArray("searchResult");
                            if (array != null && array.size() > 0){
                                jsonObject =  array.getJSONObject(0).getJSONObject("features");
                                if (jsonObject != null){
                                    return jsonObject.getString("unitName");
                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    public static String trim(String v){
        if (StringUtils.isBlank(v))return null;
        return v.trim();
    }

    /**
     * 根据外部编码来获取map
     * @param outCodes
     * @return
     */
    public static Map<String,AllocateOrderDetailBatchGetScItemResponse> getScItemMapByOutCodes(List<String> outCodes){
        Map<String,AllocateOrderDetailBatchGetScItemResponse> map = Maps.newHashMap();
        if (CollectionUtils.isEmpty(outCodes)){
            return map;
        }
        List<AllocateOrderDetailBatchGetScItemResponse> responses = batchGetScItemByOutCodeList(outCodes);

        if (CollectionUtils.isEmpty(responses)){
            return map;
        }
        map = responses.stream().filter(Objects::nonNull).collect(HashMap::new,
                (hash,scItem)->hash.put(scItem.getScItemCode(),scItem),HashMap::putAll);
        return map;
    }

    /**
     * 根据商品外部编码获取商品id
     * @param outCode
     * @return
     */
    public static String getScItemIdByOutCode(String outCode){
        String code = deleteZeroPrefix(outCode);
        if (StringUtils.isNotBlank(code)){
            BaselineQueryScItemByPageRequest baselineQueryScItemByPageRequest = new BaselineQueryScItemByPageRequest();
            baselineQueryScItemByPageRequest.setOutIdList(Lists.newArrayList(code));
            Object obj = baseDataService.baselineQueryScItemByPage(baselineQueryScItemByPageRequest);
            if (obj != null){
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
                if (jsonObject != null){
                    jsonObject = jsonObject.getJSONObject("result");
                    if (jsonObject != null){
                        jsonObject = jsonObject.getJSONObject("result");
                        if (jsonObject != null){
                            JSONArray array = jsonObject.getJSONArray("searchResult");
                            if (array != null && array.size() > 0){
                                return array.getJSONObject(0).getString("scItemId");
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    public static List<WmsSDO> batchGetWmsSDOs(List<String> areaIds){
//        WmsQueryWarehouseZoneListRequest request = new WmsQueryWarehouseZoneListRequest();
//        unifiedInventoryService.wmsQueryWarehouseZoneList()
        return null;
    }

//    public List<AllocateOrderDetailGetWarehouseResponse> batchGetWarehouse(
//            AllocateOrderDetailGetBatchWarehouseRequest request) {
//        BatchQueryWarehouseByIdsRequest r = new BatchQueryWarehouseByIdsRequest();
//        r.setWarehouseIds(request.getWarehouseIds());
//        Object obj =
//                unifiedInventoryService.batchQueryWarehouseByIds(r);
//        System.out.println(JSONObject.toJSONString(obj));
//        return convertBatchWarehouse(obj);
//    }

    public static String getStatusDesc(Integer type){
        for (AllocateOrderStatus value : AllocateOrderStatus.values()) {
            if (Objects.equals(type,value.getValue())){
                return value.getDesc();
            }
        }
        return null;
    }

    public static JSONObject getStatusEpochDesc(Integer type){
        if (type == null)return null;
        if (type.intValue() == AllocateOrderStatus.DRAFT.getValue()){
            return generateStatus(AllocateOrderStatus.DRAFT.getDesc(),"cancel");
        }else if (type.intValue() == AllocateOrderStatus.Shipment_Processing.getValue()){
            return generateStatus(AllocateOrderStatus.Shipment_Processing.getDesc(), "warning");
        }else if (type.intValue() == AllocateOrderStatus.Part_Shipped.getValue()){
            return generateStatus(AllocateOrderStatus.Part_Shipped.getDesc(),"warning");
        }else if (type.intValue() == AllocateOrderStatus.Shipped.getValue()){
            return generateStatus(AllocateOrderStatus.Shipped.getDesc(), "success");
        } else if (type.intValue() == AllocateOrderStatus.Receive_Processing.getValue()){
            return generateStatus(AllocateOrderStatus.Receive_Processing.getDesc(),"middle");
        }else if (type.intValue() == AllocateOrderStatus.Part_Received.getValue()){
            return generateStatus(AllocateOrderStatus.Part_Received.getDesc(), "middle");
        }else if (type.intValue() == AllocateOrderStatus.Received.getValue()){
            return generateStatus(AllocateOrderStatus.Received.getDesc(),"success");
        }else if (type.intValue() == AllocateOrderStatus.Cancel.getValue()){
            return generateStatus(AllocateOrderStatus.Cancel.getDesc(), "error");
        }else if (type.intValue() == AllocateOrderStatus.WAIT_PUSH.getValue()){
            return generateStatus(AllocateOrderStatus.WAIT_PUSH.getDesc(),"middle");
        }
        return null;
    }

    public static JSONObject generateStatus(String msg,String color){
        JSONObject obj = new JSONObject();
        obj.put("text",msg);
        obj.put("type",color);
        return obj;
    }

    public static String multiply(String price, String quantity){
        if (StringUtils.isAnyBlank(price,quantity)){
            return null;
        }
        BigDecimal p = new BigDecimal(price.trim());
        BigDecimal q = new BigDecimal(quantity.trim());
        BigDecimal v = p.multiply(q);
        return v.setScale(2, RoundingMode.HALF_UP).toString();
    }

    public static String getDiscountPrice(String subTotalAmount,String quantity){
        if (StringUtils.isAnyBlank(subTotalAmount,quantity)){
            return null;
        }
        BigDecimal s = new BigDecimal(subTotalAmount.trim());
        BigDecimal q = new BigDecimal(quantity.trim());
        if (q.intValue() == BigDecimal.ZERO.intValue()){
            return null;
        }
        BigDecimal v = s.divide(q,2,RoundingMode.HALF_UP);
        return v.toString();
    }
    public static String subtract(String val1,String val2){
        if (StringUtils.isBlank(val1))return null;
        if (StringUtils.isBlank(val2))return val1;
        BigDecimal var1B = new BigDecimal(val1.trim());
        BigDecimal var2B = new BigDecimal(val2.trim());
        return var1B.subtract(var2B).toString();
    }
    public static String subtract(String v1, Integer v2){
        if (StringUtils.isBlank(v1))return null;
        if (v2 == null)return v1.trim();
        BigDecimal start = new BigDecimal( v1.trim());
        BigDecimal end = new BigDecimal(v2);
        return start.subtract(end).toString();
    }

    public static String subtract(Integer v1,Integer v2){
        if (v1 == null){
            return null;
        }
        if (v2 == null){
            return v1.toString();
        }
        return String.valueOf((v1 - v2));
    }

    public static String toStr(Integer v){
        if (v == null){
            return null;
        }
        return String.valueOf(v);
    }


    public static String getScItemName(String scItemId){
        AllocateOrderDetailBatchGetScItemResponse response =  getScItem(scItemId);
        if (response != null){
            return response.getTitle();
        }
        return null;
    }

    /**
     * 获取单个货品明细
     * @param scItemId
     * @return
     */
    public static AllocateOrderDetailBatchGetScItemResponse getScItem(String scItemId){
        BaselineQueryScItemByPageRequest r = new BaselineQueryScItemByPageRequest();
        if (StringUtils.isNotBlank(scItemId)){
            r.setIdList(Lists.newArrayList(scItemId));
        }
        Object obj = baseDataService.baselineQueryScItemByPage(r);
        String s = JSON.toJSONString(obj);
        List<AllocateOrderDetailBatchGetScItemResponse> responses = convert(obj);
        if (CollectionUtils.isNotEmpty(responses)){
            return responses.get(0);
        }
        return new AllocateOrderDetailBatchGetScItemResponse();
    }

    public static Map<String,AllocateOrderDetailBatchGetScItemResponse> getScItemMap(List<String> scItemIdList){
        Map<String,AllocateOrderDetailBatchGetScItemResponse> map = Maps.newHashMap();
        List<AllocateOrderDetailBatchGetScItemResponse>  responses = batchGetScItem(scItemIdList);
        if (CollectionUtils.isEmpty(responses)){
            return map;
        }
        map = responses.stream().filter(Objects::nonNull).collect(HashMap::new,
                (hash,scItem)->hash.put(scItem.getScItemId(),scItem),HashMap::putAll);
        return map;
    }

    public static List<AllocateOrderDetailBatchGetScItemResponse> batchGetScItemByOutCodeList(List<String> outCodeList){
        List<AllocateOrderDetailBatchGetScItemResponse> responses = Lists.newArrayList();
        if (CollectionUtils.isEmpty(outCodeList)){
            return responses;
        }
        BaselineQueryScItemByPageRequest request = new BaselineQueryScItemByPageRequest();
        request.setOutIdList(outCodeList);
        Object obj = baseDataService.baselineQueryScItemByPage(request);
        responses = convert(obj);
        return responses;
    }

    public static List<AllocateOrderDetailBatchGetScItemResponse> batchGetScItem(List<String> scItemIdList){
        List<AllocateOrderDetailBatchGetScItemResponse> responses = Lists.newArrayList();
        if (CollectionUtils.isEmpty(scItemIdList)){
            return responses;
        }
        BaselineQueryScItemByPageRequest request = new BaselineQueryScItemByPageRequest();
        request.setIdList(scItemIdList);
        Object obj = baseDataService.baselineQueryScItemByPage(request);
        responses = convert(obj);
        return responses;
    }

    public static List<AllocateOrderDetailBatchGetScItemResponse> batchGetScItem(
            AllocateOrderDetailBatchGetScItemRequest request) {
        BaselineQueryScItemByPageRequest r = new BaselineQueryScItemByPageRequest();
        if (CollectionUtils.isNotEmpty(request.getScItemIdList())){
            r.setIdList(request.getScItemIdList());
        }
        Object obj = baseDataService.baselineQueryScItemByPage(r);
        String s = JSON.toJSONString(obj);
        System.out.println(s);
        List<AllocateOrderDetailBatchGetScItemResponse> responses = convert(obj);
        return responses;
    }


    public static List<AllocateOrderDetailBatchGetScItemResponse> convert(Object obj){
        String s = JSONObject.toJSONString(obj);
        JSONObject object = JSONObject.parseObject(s);
        JSONArray array =
                object.getJSONObject("result").getJSONObject("result").getJSONArray("searchResult");
        List<AllocateOrderDetailBatchGetScItemResponse> responses = Lists.newArrayList();
        if (array != null && array.size() > 0){
            for (int i =0; i< array.size();i++){
                AllocateOrderDetailBatchGetScItemResponse r = new AllocateOrderDetailBatchGetScItemResponse();
                JSONObject j = array.getJSONObject(i);
                String scItemId = j.getString("scItemId");
                String title = j.getString("title");
                String scItemCode = j.getString("outerId");
                r.setScItemId(scItemId);
                r.setTitle(title);
                r.setScItemCode(scItemCode);
                r.setFeatures(JSONObject.parseObject(j.getString("features"), Map.class));
                responses.add(r);
            }
        }
        return responses;
    }

}
